import React, { useState, useEffect, useContext } from 'react'
import { reqcartadd, reqgetgoodsinfo } from '../../http/api'
import Header from "../../components/Header/Header"
import {MyContext} from "../../App"
import "./detail.less"
import { Toast } from 'antd-mobile'

const Detail = () => {
    //初始化
    const [list, setList] = useState([])
    const [isshow, setIsshow] = useState(false)
    const [num, setNum] = useState(1)
    const { state: { pre }, dispatch } = useContext(MyContext)


    //做逻辑
    //获取list
    const reqList = () => {
        reqgetgoodsinfo({ id: 1 }).then(res => {
            if (res.data.code == 200) {
                setList(res.data.list)
            }
        })
    }
    //点击加入购物车弹出
    const changeIsshow=(isshow)=>{
        setIsshow(isshow)
    }
    //数量加
    const numjia=()=>{
        setNum(num+1)
    }
    //数量减
    const numjian=()=>{
        if(num<=1){
            return
        }
        setNum(num-1)
    }
    //加入购物车
    const reqinfo=()=>{
        let uid = JSON.parse(sessionStorage.getItem("info")).uid
        // console.log(list[0].id);
        let goodsid = list[0].id
        let num = list[0].num
        reqcartadd({uid,type:1,goodsid,num}).then(res=>{
            if(res.data.code==200){
                Toast.show({
                    content:res.data.msg
                })
                setIsshow(false)
            }
        })
    }

    useEffect(() => {
        //获取list
        reqList()
    }, [])


    return (
        <div className='detail'>
            <Header text="商品详情" back></Header>
            <div className='con'>
                {list.map((item, index) => {
                    return (
                        <div key={index}>
                            <img src={pre + item.img} alt="" />
                            <p>价格：{item.price} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;原价:{item.market_price}</p>
                            <p>{item.description}</p>
                            <p>{item.goodsname}</p>
                        </div>
                    )
                })}
                <div className='button'>
                    <button onClick={() => changeIsshow(true)}>加入购物车</button>
                </div>
            </div>
            {isshow ? (
                <div className='mengban' onClick={(e) => e.target.className == "mengban" ? changeIsshow(false) : null}>
                    <div>
                        <span onClick={() => changeIsshow(false)}>X</span>
                        <p>数量：</p>
                        <p><button onClick={() =>numjian()}>-</button><span>{num}</span><button onClick={() => { numjia() }}>+</button></p>
                        <button onClick={() => reqinfo()}>加入购物车</button>
                    </div>
                </div>
            ) : null}
        </div>
    )
}

export default Detail